package com.xusheng.cli.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.MyServiceImpl;
import com.xusheng.cli.entity.frontUserModule.FrontUser;
import com.xusheng.cli.entity.frontUserModule.VipConfig;
import com.xusheng.cli.entity.rechargeModule.Recharge;
import com.xusheng.cli.entity.vipRecordModule.VipRecord;
import com.xusheng.cli.mapper.FrontUserMapper;
import com.xusheng.cli.mapper.RechargeMapper;
import com.xusheng.cli.mapper.VipConfigMapper;
import com.xusheng.cli.mapper.VipRecordMapper;
import com.xusheng.cli.req.RechargeQueryReq;
import com.xusheng.cli.service.RechargeService;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 充值表(Recharge)表服务实现类
 *
 * @author 王鹤然
 * @since 2023-07-03 12:38:12
 */
@Slf4j
@Service("rechargeService")
public class RechargeServiceImpl extends MyServiceImpl<RechargeMapper, Recharge> implements RechargeService {

    @Resource
    private VipConfigMapper vipConfigMapper;
    @Resource
    private VipRecordMapper vipRecordMapper;
    @Resource
    private FrontUserMapper frontUserMapper;

    @Override
    public Boolean confirmPay(String orderNo) {
        // 根据订单号获取订单数据
        Recharge order = getOne(new QueryWrapper<>(new Recharge()).lambda().eq(Recharge::getOrderNumber, orderNo).last("limit 1"));
        // 订单已经处理过，直接返回success
        if (order.getPayInfo()) {
            log.info("充值订单：{}，充值成功", orderNo);
            return false;
        }
        // 计算会员天数
        // 获取会员信息
        VipConfig vipConfig = vipConfigMapper.selectById(order.getVipId());
        // type:0次  1天  2月
        Integer days = vipConfig.getDays();
        Integer type = vipConfig.getType();
        // 充值类型 1：会员充值 2：钱包充值 3：会员兑换
        Integer rechargeType = vipConfig.getRechargeType();
        Integer present = vipConfig.getPresent();
        // 更新用户信息
        FrontUser frontUser = frontUserMapper.selectById(order.getPlayerId());
        LocalDateTime vipExpires;
        if (frontUser.getVipExpires() == null || frontUser.getVipExpires().isBefore(LocalDateTime.now())) {
            vipExpires = LocalDateTime.now();
        } else {
            vipExpires = frontUser.getVipExpires();
        }
        if (rechargeType == 1) {
            if (type == 0) {
                // 添加次数
                frontUser.setWatchCount(frontUser.getWatchCount() + 1);
            } else if (type == 1) {
                // 添加天数
                frontUser.setVipExpires(vipExpires.plusDays(days + present));
                frontUser.setVipId(vipConfig.getId());
            } else if (type == 2) {
                // 添加月数
                frontUser.setVipExpires(vipExpires.plusMonths(days).plusDays(present));
                frontUser.setVipId(vipConfig.getId());
            }
        } else if (rechargeType == 2) {
            frontUser.setVipId(vipConfig.getId());
            frontUser.setGold(frontUser.getGold() + order.getRechargeAmount().intValue());
        }

        log.info("更新用户信息：{}", frontUser);
        frontUserMapper.updateById(frontUser);
        // 更新saToken用户信息
//        StpPlayerUtil.getSession().set(Constant.PLAYER, frontUser);
        log.info("用户信息更新完成");
        // 会员记录表加数据
        VipRecord record = new VipRecord();
        record.setUserId(order.getPlayerId());
        record.setUserName(order.getPlayerAccount());
        record.setVipId(vipConfig.getId());
        record.setVipName(vipConfig.getName());
        record.setAmount(vipConfig.getAmount());
        log.info("添加会员记录：{}", record);
        vipRecordMapper.insert(record);
        log.info("会员记录添加完成");
        // 更新订单状态
        order.setPayTime(LocalDateTime.now());
        order.setPayInfo(true);
        log.info("更新订单状态：{}", order);
        updateById(order);
        log.info("订单状态更新完成");
        return true;
    }

    @Override
    public MyPage<Recharge> queryByPage(MyPage<Recharge> page, RechargeQueryReq req) {
        LocalDateTime start = null, end = null;
        if (req.getStartTime() != null) {
            start = LocalDateTime.of(req.getStartTime(), LocalTime.of(0, 0, 0));
        }
        if (req.getEndTime() != null) {
            end = LocalDateTime.of(req.getEndTime(), LocalTime.of(23, 59, 59));
        }
        JoinLambdaWrapper<Recharge> wrapper = new JoinLambdaWrapper<>(Recharge.class);
        wrapper.orderByDesc(Recharge::getCreateTime)
                .gt(start != null, Recharge::getCreateTime, start)
                .lt(end != null, Recharge::getCreateTime, end)
                .like(StrUtil.isNotBlank(req.getPlayerAccount()), Recharge::getPlayerAccount, req.getPlayerAccount())
                .leftJoin(VipConfig.class, VipConfig::getId, Recharge::getVipId)
                .selectAs(VipConfig::getName, "vipName")
                .end();
        return baseMapper.joinSelectPage(req.getPage(), wrapper, Recharge.class);
    }

    /**
     * 统计订单金额
     *
     * @param req
     * @return
     */
    @Override
    public BigDecimal statisticsAmount(RechargeQueryReq req) {
        LocalDateTime start = null, end = null;
        if (req.getStartTime() != null) {
            start = LocalDateTime.of(req.getStartTime(), LocalTime.of(0, 0, 0));
        }
        if (req.getEndTime() != null) {
            end = LocalDateTime.of(req.getEndTime(), LocalTime.of(23, 59, 59));
        }
        return baseMapper.statisticsAmount(start, end, req.getPlayerAccount());
    }
}

